package com.lemon.reggie.task;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ArrayUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.lemon.reggie.pojo.entity.Dish;
import com.lemon.reggie.pojo.entity.Setmeal;
import com.lemon.reggie.service.DishService;
import com.lemon.reggie.service.SetmealService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.File;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import java.util.stream.Stream;

//@Scheduled 默认是单线程
@Slf4j
@Component
public class CleanPictureTask {

    @Value("${upload.dir}")
    private String uploadDir;
    @Resource
    private DishService dishService;
    @Resource
    private SetmealService setmealService;

    /**
     * 清理菜品套餐垃圾图片
     * @return void
     * @author Guannankun
     * @since 2022/8/17
     */
    @Scheduled(cron = "${clean.cron}")
    //使用自定义的多线程
    @Async("myExecutor")
    public void cleanPicture() {
        log.info("{}线程开始执行任务。。。", Thread.currentThread().getName());
        File dirFile = new File(uploadDir);
        if (!dirFile.exists()) {
            dirFile.mkdir();
        }
        File[] files = dirFile.listFiles();
        if (ArrayUtil.isNotEmpty(files)) {
            //大集合(正式对象存储)
            List<String> fileNames = Stream.of(files).filter(File::isFile)
                    .map(File::getName).collect(Collectors.toList());

            //小集合DB
            List<String> dishImages = dishService.list(new LambdaQueryWrapper<Dish>().select(Dish::getImage))
                    .stream().map(Dish::getImage).collect(Collectors.toList());
            List<String> setMealImages =
                    setmealService.list(new LambdaQueryWrapper<Setmeal>().select(Setmeal::getImage))
                    .stream().map(Setmeal::getImage).collect(Collectors.toList());
            dishImages.addAll(setMealImages);

            //计算两个集合的差
            Collection<String> disjunction = CollUtil.disjunction(fileNames, dishImages);
            List<String> deleteImages = new ArrayList<>(disjunction);

            //删除垃圾图片
            for (File file : files) {
                for (String deleteImage : deleteImages) {
                    if (Objects.equals(file.getName(), deleteImage)) {
                        file.delete();
                        log.info("----- 删除垃圾图片:{}成功", file.getName());
                        break;
                    }
                }
            }
        }
    }
}
